package lab;

import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;

import java.sql.*;

public class Insert_to_tangshi {
    public static void main(String[] args) throws SQLException {
        String dynasty="唐代";
        String author="白居易";
        String title="问刘十九";
        String content="绿蚁新醅酒，红泥小火炉。晚来天欲雪，能饮一杯无？";

        //之前的方法
        //1.注册driver
        //2.获取connection 通过DriverManager
        /*
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://127.0.0.1/java20210125?useSSL=false&characterEncoding=utf8";
        Connection connection= DriverManager.getConnection(url,"root","missh111");
        */

        //便捷方法
        //通过datasource获取connection
        //DataSource dataSource=new  MysqlDataSource();不带连接池
        MysqlConnectionPoolDataSource dataSource=new MysqlConnectionPoolDataSource();//连接池,好处参照线程池
        dataSource.setServerName("127.0.0.1");
        dataSource.setPort(3306);
        dataSource.setUser("root");
        dataSource.setPassword("missh111");
        dataSource.setDatabaseName("java20210125");
        dataSource.setUseSSL(false);
        dataSource.setCharacterEncoding("UTF8");

        try (Connection connection=dataSource.getConnection()){
            String sql="Insert INTO tangshi"+
                    "(sha256,dynasty,title,author,content,words)"
                    +"VALUES(?,?,?,?,?,?)";
            PreparedStatement statement=connection.prepareStatement(sql);
            statement.setString(1,"sha256");
            statement.setString(2,dynasty);
            statement.setString(3,title);
            statement.setString(4,author);
            statement.setString(5,content);
            statement.setString(6,"");

            statement.executeUpdate();
        }
    }
}
